<?php

namespace Dcat\Admin\Caijiwebinfo\Forms;

use Dcat\Admin\Admin;
use Dcat\Admin\Caijiwebinfo\CaijiwebinfoServiceProvider;
use Dcat\Admin\Caijiwebinfo\Models\CaijiwebinfoCms;
use Dcat\Admin\Caijiwebinfo\Models\CaijiwebinfoMedia;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;


class GetWxgzhArt extends Form implements LazyRenderable {
    use LazyWidget; // 使用异步加载功能

    public $source_url;
    public $source_title;
    public $is_use_cache = 1;
    public $caiji_web_url;

    /**
     * @desc 解释获取资源地址
     * @param $html
     * @return array
     * author eRic
     * dateTime 2024-08-14 21:06
     */
    public function extractImageUrls($html) {
        $pattern = '/<img[^>]+src="([^"]+)"/';
        preg_match_all($pattern, $html, $matches);

        $arr = [];
        if (!empty($matches[1])) {
            foreach ($matches[1] as $imgo) {
                // 检查是不是有效的url
                if (!filter_var($imgo, FILTER_VALIDATE_URL)) {
                    continue;
                }
                $imgar = explode('?', $imgo);
                $ext   = '';
                if (!empty($imgar[0])) {
                    if (strpos($imgar[0], '_gif')) {
                        $ext = '.gif';
                    }
                    if (strpos($imgar[0], '_png')) {
                        $ext = '.png';
                    }
                    if (strpos($imgar[0], '_jpg')) {
                        $ext = '.jpg';
                    }
                    if (strpos($imgar[0], '_jpeg')) {
                        $ext = '.jpg';
                    }
                    if (strpos($imgar[0], '_webp')) {
                        $ext = '.webp';
                    }
                }
                $arr[] = [
                    'orgin'   => $imgo,
                    'new_img' => $imgar[0],
                    'ext'     => $ext,
                ];
            }

            return $arr;
        }

        return $matches[1];
    }

    /**
     * @desc 单个文件上传到cos
     * @param $img
     * * @param $img
     * author eRic
     * dateTime 2024-08-14 20:17
     */
    public function upfileToCos($localPath, $cospath) {
        if (!file_exists($localPath)) {
            return false;
        }

        $region    = CaijiwebinfoServiceProvider::setting('region');
        $secretId  = CaijiwebinfoServiceProvider::setting('secretId');
        $secretKey = CaijiwebinfoServiceProvider::setting('secretKey');
        $Bucket    = CaijiwebinfoServiceProvider::setting('Bucket');
        $domain    = CaijiwebinfoServiceProvider::setting('domain');
        $appId     = CaijiwebinfoServiceProvider::setting('appId');

        $urlParts = parse_url($domain);

        $protocol = isset($urlParts['scheme']) ? $urlParts['scheme'] : 'https';
        $host     = isset($urlParts['host']) ? $urlParts['host'] : '';
        if (empty($host)) {
            $host = isset($urlParts['path']) ? $urlParts['host'] : 'path';
        }

        $cos_config = [
            //'domain'      => $domain,
            'region'      => $region,
            //'scheme' => 'https', //协议头部，默认为http
            'credentials' => [
                'appId'     => $appId,
                'secretId'  => $secretId,
                'secretKey' => $secretKey
            ]
        ];
        if (!empty($domain)) {
            $cos_config['domain'] = $host; //自定义域名
        }

        $cosClient = new \Qcloud\Cos\Client($cos_config);
        try {
            // 尝试三次
            for ($i = 1; $i <= 3; $i++) {
                $result = $cosClient->putObject(array(
                    'Bucket' => $Bucket,
                    'Key'    => $cospath,
                    'Body'   => fopen($localPath, 'rb')
                ));
                if (!empty($result['Location'])) {
                    break;
                }
            }
        } catch (\Error $error) {

        } catch (\Exception $exception) {

        }

        if (!empty($result['Location'])) {
            /*if(empty($cos_config['domain'])){
                $save_path      = CaijiwebinfoServiceProvider::setting('save_path');
                $substring = strstr($result['Location'], $save_path, true);
                $new_web_url = str_replace($substring,$domain,$result['Location']);
                return $new_web_url;
            }*/

            return 'https://' . $result['Location'];

        }

        return false;
    }

    // 把图片资源换换算成新的数组
    public function downNewimglist($imgarr) {
        $save_path    = CaijiwebinfoServiceProvider::setting('save_path');
        $down_imglist = [];
        foreach ($imgarr as $key => &$itelk) {
            $filename       = 'wxghz-' . Str::random(20) . $itelk['ext'];
            $file_path      = $save_path . '/' . $filename; // 文件路径
            $localPath      = public_path($file_path);
            $down_imglist[] = [
                'file_path'       => $file_path,
                'res_url'         => $itelk['new_img'],
                'local_save_path' => $localPath,
                'retry'           => 0,
            ];
        }
        if (!empty($down_imglist)) {
            $this->downloadImages($down_imglist);
            //$this->downloadImagesConcurrently($down_imglist);
        }

        // 检查图片是不是下载好了
        foreach ($down_imglist as $key => $itemp) {
            $arrkey = $this->getArrKey($itemp['res_url'], $imgarr);
            //$imgarr[$arrkey]['file_path'] = $itemp['file_path'];
            $imgarr[$arrkey]['media_size'] = 0;
            if (file_exists($itemp['local_save_path'])) {
                $imgarr[$arrkey]['local_web_url'] = env('APP_URL') . $itemp['file_path'];
                $imgarr[$arrkey]['media_size']    = filesize($itemp['local_save_path']);
            } else {
                $imgarr[$arrkey]['local_web_url'] = '';
            }
        }
        return $imgarr;
    }

    // 根据值查找二维数组的键值
    public function getArrKey($val, $arr) {
        foreach ($arr as $key => $itemm) {
            if ($itemm['new_img'] == $val) {
                return $key;
            }
        }
        return '';
    }

    /**
     * @desc 批量下载媒体资源到本地
     * @param $imgarr
     * author eRic
     * dateTime 2024-08-19 23:49
     */
    public function downMediaToLocal($imgarr) {
        $save_path         = CaijiwebinfoServiceProvider::setting('save_path');
        $resources_save    = CaijiwebinfoServiceProvider::setting('resources_save');
        $clear_local_media = CaijiwebinfoServiceProvider::setting('clear_local_media');
        $is_use_cache      = $this->is_use_cache;
        // 筛选出本地没有，需要下载的图片列表
        $down_imglist    = []; //需要下载的图片列表
        $local_imglist   = []; // 原有的下载资源
        $yi_down_imglist = []; // 需要下载的图片，已完成的

        if (!empty($is_use_cache) && $is_use_cache == 2) { // 不用缓存
            $down_imglist = $imgarr;
        } else {
            foreach ($imgarr as $key => $itels) {
                $media = $this->checkLocalSource($itels['new_img']);
                if (!is_array($media)) {
                    $down_imglist[] = $itels;
                } else {
                    // 需要上传cos，但是本地又没有上传过cos
                    if ($resources_save == 'cos' && empty($media['cos_web_url'])) {
                        $local_path      = str_replace(env('APP_URL'), '', $media['local_web_url']);
                        $local_file_path = public_path($local_path);
                        if (file_exists($local_file_path) && filesize($local_file_path) > 1) {
                            $media['cos_web_url'] = $this->upfileToCos($local_file_path, $local_path);
                            if (!empty($media['cos_web_url'])) {
                                // 更新到数据库
                                CaijiwebinfoMedia::where(['local_web_url' => $media['local_web_url']])->update(['cos_web_url' => $media['cos_web_url']]);
                            }
                        }

                    }
                    $lp              = [
                        'media_size'    => $media['media_size'],
                        'local_web_url' => !empty($media['local_web_url']) ? $media['local_web_url'] : '',
                        'cos_web_url'   => !empty($media['cos_web_url']) ? $media['cos_web_url'] : '',
                    ];
                    $local_imglist[] = array_merge($itels, $lp);
                }
            }
        }

        if (!empty($down_imglist)) {
            // 多线程去下载图片到本地
            $yi_down_imglist = $this->downNewimglist($down_imglist);
        }
        // 需要上传到cos的
        if (!empty($yi_down_imglist)) {
            foreach ($yi_down_imglist as $key => &$items) {
                if ($resources_save == 'cos' && !empty($items['local_web_url'])) {
                    $file_path  = str_replace(env('APP_URL'), '', $items['local_web_url']);
                    $res_imgurl = $this->upfileToCos(public_path($file_path), $file_path);
                    if ($res_imgurl === false) { // 如果上传失败


                    } else { // 上传成功
                        // 删除本地资源
                        if (!empty($clear_local_media)) {
                            @unlink(public_path($file_path));
                            $items['local_web_url'] = '';
                        } else {
                            $items['local_web_url'] = env('APP_URL') . $file_path;
                        }

                        $items['cos_web_url'] = $res_imgurl;
                    }
                }
            }
        }
        $new_imgarr = array_merge($local_imglist, $yi_down_imglist);

        // 保存下载资源记录
        $this->saveMediaData($new_imgarr);
        return $new_imgarr;
    }

    /**
     * @desc 保存记录到本地
     * @param $imgarr
     * author eRic
     * dateTime 2024-08-20 00:13
     */
    public function saveMediaData($imgarr) {
        $post_data = [];
        foreach ($imgarr as $key => $items) {
            /*$where = [
                'caiji_web_url' => $this->source_url,
                'source_url' => $items['new_img'],
            ];*/
            if (!empty($items['local_web_url']) || !empty($items['cos_web_url'])) {
                $data = [
                    'source_url'     => $items['new_img'],
                    'local_web_url'  => !empty($items['local_web_url']) ? $items['local_web_url'] : '',
                    'cos_web_url'    => !empty($items['cos_web_url']) ? $items['cos_web_url'] : '',
                    'media_size'     => !empty($items['media_size']) ? $items['media_size'] : '',
                    'source_url_md5' => md5($items['orgin']),
                ];
                if (!empty($this->caiji_web_url)) {
                    $data['caiji_web_url'] = $this->caiji_web_url;
                }
                $post_data [] = $data;
            }

            //CaijiwebinfoMedia::create($data);
        }
        DB::table('caijiwebinfo_media')->insert($post_data);
    }

    // 多线程下载图片
    public function downloadImages($imgarr) {
        try {
            $mh      = curl_multi_init();
            $handles = [];

            foreach ($imgarr as $i => $itemss) {
                $ch       = curl_init();
                $filename = $itemss['local_save_path'];
                $fp       = fopen($filename, 'w');
                curl_setopt($ch, CURLOPT_URL, $itemss['res_url']);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_FILE, $fp);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_TIMEOUT, 60);
                curl_setopt($ch, CURLOPT_REFERER, $itemss['res_url']);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                $handles[$i] = ['ch' => $ch, 'fp' => $fp];

                curl_multi_add_handle($mh, $ch);
            }


            $running = null;
            $i       = 1;
            do {
                /*if($i >= 100000){ //防止死循环
                    break;
                }*/
                curl_multi_exec($mh, $running);
                $i++;
            } while ($running > 0);

            foreach ($handles as $handle) {
                curl_multi_remove_handle($mh, $handle['ch']);
                curl_close($handle['ch']);
                fclose($handle['fp']);
            }
            curl_multi_close($mh);
        } catch (\Error $error) {

        } catch (\Exception $exception) {

        }
    }


    public static function startWith($haystack, $needles) {
        foreach ((array)$needles as $needle) {
            if ($needle != '' && mb_strpos($haystack, $needle) === 0) {
                return true;
            }
        }
        return false;
    }

    // 验证本地是否有图片
    public function checkLocalSource($img_url) {
        $media_info = CaijiwebinfoMedia::where(['source_url' => $img_url])->orderBy('id', 'DESC')->first();
        if (!empty($media_info->id)) {
            return [
                'local_web_url' => $media_info->local_web_url,
                'cos_web_url'   => $media_info->cos_web_url,
                'media_size'    => $media_info->media_size,
            ];
        }
        return false;
    }

    /**
     * @desc 下载资源并保存到本地 并替换原来的地址
     * @param $art_html 原文章内容
     * @return mixed
     * author eRic
     * dateTime 2024-08-14 18:00
     */
    public function downToReplaceResourcePath($art_html) {
        $save_path      = CaijiwebinfoServiceProvider::setting('save_path');
        $resources_save = CaijiwebinfoServiceProvider::setting('resources_save');
        $imgarr_orign   = $this->extractImageUrls($art_html); // 匹配出图片地址
        $imgarr         = $this->downMediaToLocal($imgarr_orign);
        foreach ($imgarr as $key => $items) {
            if ($resources_save == 'cos') {
                if (!empty($items['cos_web_url'])) {
                    $art_html = str_replace($items['orgin'], $items['cos_web_url'], $art_html);
                }
            } else {
                // 本地储存
                if (!empty($items['local_web_url'])) {
                    $art_html = str_replace($items['orgin'], $items['local_web_url'], $art_html);
                }
            }

        }
        return str_replace('data-src', 'src', $art_html);
    }

    public function fenxipage($page_html) {
        $page_html = file_get_contents(public_path('caijiwebinfo/tp.txt'));
        libxml_use_internal_errors(true);
        $dom = new \DOMDocument();
        $dom->loadHTML($page_html);
        libxml_clear_errors();
        $title = $dom->getElementById('activity-name')->nodeValue;

        $xpath        = new \DOMXPath($dom);
        $riestDiv     = $xpath->query('//div[contains(@class, "rich_media_content")]')->item(0);
        $riestContent = '';
        if ($riestDiv) {
            $riestContent = $dom->saveHTML($riestDiv);
        }
        return [
            'code' => 0,
            'data' => [
                'title'   => trim($title),
                'content' => $riestContent
            ]
        ];
    }

    // 采集公众号页面
    public function caijiWxartContent($web_url) {
        return $this->fenxipage($response = '');
        // 初始化 cURL
        $ch = curl_init();

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $web_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 执行 cURL 请求
        $response = curl_exec($ch);

        // 检查是否有错误发生
        if ($response === false) {
            return [
                'code' => -1,
                'msg'  => '采集遇到问题',
            ];
        } else {
            // 输出采集到的网页内容
            return $this->fenxipage($response);
            //return $response;
        }

        // 关闭 cURL 资源
        curl_close($ch);
    }

    /**
     * Handle the form request.
     * https://mp.weixin.qq.com/s/OPVLPlr8weKRCA11ypSing
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input) {
        $caiji_apihost     = CaijiwebinfoServiceProvider::setting('caiji_apihost');
        $caiji_token       = CaijiwebinfoServiceProvider::setting('caiji_token');
        $resources_save    = CaijiwebinfoServiceProvider::setting('resources_save');
        $is_resources_save = CaijiwebinfoServiceProvider::setting('is_resources_save');
        //$caijiqi_type      = CaijiwebinfoServiceProvider::setting('caijiqi_type');
        $is_save_log       = CaijiwebinfoServiceProvider::setting('is_save_log');
        if (empty($caiji_apihost)) {
            return $this->response()->error('请在扩展配置中 配置采集器api域名');
        }
        if (empty($caiji_token)) {
            return $this->response()->error('请在扩展配置中 配置采集器token');
        }

        $save_path = CaijiwebinfoServiceProvider::setting('save_path');
        $localPath = public_path($save_path);
        if (empty($localPath)) {
            return $this->response()->error('请在扩展配置中 配置资源储存路径');
        }
        // 检查储存路径有没有权限
        if (!is_dir($localPath)) {
            mkdir($localPath, 0777);
        }
        if ($resources_save == 'cos') {
            $validator = \Validator::make(CaijiwebinfoServiceProvider::setting(), [
                'region'    => 'required',
                'secretId'  => 'required',
                'secretKey' => 'required',
                'Bucket'    => 'required',
            ], [
                'region.required'    => '区域 不能为空',
                'secretId.required'  => 'secretId 不能为空',
                'secretKey.required' => 'secretKey 不能为空',
                'Bucket.required'    => '存储桶名称 不能为空',
            ]);
            if ($validator->fails()) {
                return $this->response()->error($validator->errors()->first());
            }
        }
        $editor_type = $input['editor_type'];
        cache()->put('editor_type', $editor_type, 1200000);
        $wxgzh_url = $input['wxgzh_url'];

        $platform = $input['platform'];
        cache()->put('caijiwebinfo_web_url', $wxgzh_url);
        cache()->put('caijiwebinfo_platform', $platform);
        $this->is_use_cache  = $input['is_use_cache'];
        $this->caiji_web_url = $wxgzh_url;
        $title_class         = !empty($this->payload['title_class']) ? $this->payload['title_class'] : '';
        $content_class       = !empty($this->payload['content_class']) ? $this->payload['content_class'] : '';
        if (empty($content_class)) {
            return $this->response()->error('请传入编辑器定义的class');
        }
        $form_params = [
            'token'    => $caiji_token,
            'platform' => $platform,
            'web_url'  => $wxgzh_url
        ];

        // 根据配置使用采集方式
        $caijiqi_type = 'api';
        if ($caijiqi_type == 'api') {
            $client = new \GuzzleHttp\Client();
            try {
                // 尝试三次
                for ($i = 1; $i <= 3; $i++) {
                    $res      = $client->post($caiji_apihost . '/api/aigc_tools/network/caijiwebinfo', [
                        'form_params' => $form_params,
                        'timeout'     => 60,
                        'http_errors' => false,
                        'verify'      => false,
                    ]);
                    $content  = $res->getBody()->getContents();
                    $contents = json_decode($content, true);
                    if (isset($contents['code']) && $contents['code'] == 0) {
                        break;
                    }
                }
            } catch (\Error $error) {

            } catch (\Exception $exception) {

            }
        } else {
            $contents = $this->caijiWxartContent($wxgzh_url);
            if (isset($contents['code']) && $contents['code'] == -1) {
                return $this->response()->error($contents['msg']);
            }
        }


        if (isset($contents['code']) && $contents['code'] == -1) {
            return $this->response()->error($contents['msg']);
        }
        if (empty($contents['data']['content'])) {
            return $this->response()->error('获取微信文章内容失败');
        }
        $art_title          = $contents['data']['title'];
        $htmlkk             = $contents['data']['content'];
        $this->source_title = $art_title;
        $this->source_url   = $wxgzh_url;
        if ($is_resources_save == 2) {
            $html_new = $this->downToReplaceResourcePath($htmlkk);
        } else {
            $html_new = $htmlkk;
        }

        $title_class   = '.field_' . $title_class;
        $content_class = '.field_' . $content_class;
        // tinymce 编辑器
        if ($editor_type == 'tinymce') {
            $jscode = <<<JS
       $('$title_class').val('$art_title');
       var editorid = $('$content_class').attr('id');
console.log(editorid);
       var editor = tinymce.get(editorid);
           editor.setContent(`$html_new`);
           tinymce.execCommand('mceFocus',false,editorid);
           $('.modal').modal('hide');
JS;
        }
        // neditor 编辑器
        if ($editor_type == 'neditor') {

            $jscode = <<<JS
            $('$title_class').val('$art_title');
var editorid = $('$content_class').attr('id');
console.log('neditor--'+editorid);
var editor = UE.getEditor(editorid);
       editor.setContent(`$html_new`);
           $('.modal').modal('hide');
JS;
        }

        // baidu 编辑器
        if ($editor_type == 'baidu') {
            $jscode = <<<JS
            $('$title_class').val('$art_title');
var editorid = $('$content_class').attr('id');
console.log('baidu--'+editorid);
var editor = UE.getEditor(editorid);
       editor.execCommand('insertHtml', `$html_new`);
           $('.modal').modal('hide');
JS;
        }

        if ($editor_type == 'wang-editor') {
            /*$jscode        = <<<JS
            $('$title_class').val('$art_title');
var editorid = $('$content_class').attr('id');
console.log('wang-editor--'+editorid);
var EE = window.wangEditor;
var editor = EE.getEditor('#' + editorid);
       editor.setHtml(`$html_new`);
            $('.modal').modal('hide');
JS;*/
            return $this->response()->error('暂不支持 wang-editor');
        }
        // 开启日志
        if (!empty($is_save_log)) {
            $info = CaijiwebinfoCms::addlogs([
                'user_id'  => Admin::user()->id,
                'web_url'  => $wxgzh_url,
                'platform' => $platform,
                'title'    => $art_title,
                'content'  => $html_new,
            ]);
            CaijiwebinfoMedia::where(['caiji_web_url' => $wxgzh_url])->update(['cms_id' => $info->id]);
        }
        return $this
            ->response()
            ->success('获取微信文章成功')->script($jscode);
    }

    /**
     * Build a form here.
     */
    public function form() {
        $this->width(9, 3);
        $this->html(Alert::make('如出现被 [135编辑器] 遮挡的情况，请刷新一下页面即可', '提示')->info());
        $editor_type = cache()->get('editor_type', 'neditor');
        $this->radio('editor_type', '编辑器类型')->help('选择你当前使用的是哪一款编辑器')
            ->options(['tinymce' => 'tinymce', 'neditor' => '135编辑器', 'baidu' => 'baidu'])
            ->default($editor_type)
            ->required();
        $this->radio('is_use_cache', '使用历史缓存')->options(['1' => '默认使用', '2' => '不使用'])->default('1')->value('1');
        $this->radio('platform', '网络平台')
            ->options(CaijiwebinfoCms::Platform_arr)
            ->default('wxgzh')->help('暂时只支持[微信公众号]')->required();
        $this->url('wxgzh_url', '网络链接地址')->help('例:https://mp.weixin.qq.com/s/AnPrPYGtB-bMhbty_uB0PQ')->required();
        $this->disableResetButton();
    }

}
